<template>
  <el-dialog
    v-model="state.dialogVisible"
    :append-to-body="true"
    :before-close="close"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    :destroy-on-close="true"
    top="5vh"
    :modal="model"
    :title="state.dialogTitle"
    :width="width"
    draggable
  >
    <el-form
      ref="dataFormRef"
      v-loading="state.loading"
      :model="form"
      :rules="dataRules"
      label-width="100px"
      :disabled="state.operType === 'view'"
    >
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item
            :label="translate('flow.order.orderName')"
            prop="orderName"
          >
            <el-input
              v-model="form.orderName"
              :placeholder="translate('flow.order.orderName')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="translate('flow.order.groupId')" prop="groupId">
            <DictSelect
              v-model:defaultValue="form.groupId"
              dict-code="order_flow_group"
              :width="300"
              placeholder="请选择工单分组"
              show-all="N"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="translate('flow.order.status')" prop="status">
            <DictSelect
              v-model:default-value="form.status"
              dict-code="order_status"
              expanding
              show-all="N"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设置图标" prop="icon">
            <IconEdit v-model="form.icon" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="translate('flow.order.sort')" prop="sort">
            <el-input-number
              v-model="form.sort"
              :min="1"
              :max="1000"
              :placeholder="translate('flow.order.sort')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="发起时执行" prop="flowKey">
            <CommonSelect
              v-model:defaultValue="form.flowKey"
              placeholder="请输入流程key或者流程名称后检索"
              label="flowFullName"
              value="flowKey"
              url="/esflow/def/get/latest/list"
              :width="220"
              @change="handleFlowChange"
            />
            <span style="margin: 0px 10px">的</span>
            <el-radio-group v-model="form.flowWay">
              <el-radio value="0" label="最新版本"></el-radio>
              <el-radio value="1" label="当前版本"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="translate('flow.order.remark')" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :placeholder="translate('flow.order.remark')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-if="state.operType !== 'view'" #footer>
      <span class="dialog-footer">
        <el-button @click="close">{{ translate("buttons.cancel") }}</el-button>
        <el-button type="primary" :disabled="state.loading" @click="onSubmit">
          {{ translate("buttons.confirm") }}</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="OrderEditDialog">
import { useMessage } from "@/hooks/message";
import { getObj, addObj, updateObj } from "@/api/flow/order";
import { ref } from "vue";
import { validNumber } from "@/utils/rules";
import { translate } from "@/plugins/i18n";
import DictSelect from "@/components/dictSelect.vue";
import CommonSelect from "@/components/commonSelect.vue";

const props = defineProps({
  title: {
    type: String,
    default: "工单"
  },
  width: {
    type: String,
    default: "60%"
  },
  model: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(["refresh"]);

// 定义变量内容
const dataFormRef = ref();

onMounted(() => {});

const state = reactive({
  dialogTitle: props.title,
  dialogVisible: false,
  loading: false,
  operType: false
});

// 提交表单数据
const form = ref({
  id: "",
  orderName: "",
  flowKey: "",
  groupId: "",
  status: "-1",
  remark: "",
  sort: 1,
  orderIcon: "",
  flowWay: "0",
  version: null,
  defFlowId: "",
  formId: "",
  formName: "",
  icon: {
    name: "file-icons:omnigraffle",
    bgc: "#4C87F3",
    color: "#FFFFFF"
  }
});

// 定义校验规则
const dataRules = ref({
  orderName: [
    {
      required: true,
      message: "工单名称不能为空",
      trigger: "blur"
    }
  ],
  flowKey: [
    { required: true, message: "请选择启动时执行的流程", trigger: "blur" }
  ],
  groupId: [{ required: true, message: "分组名称不能为空", trigger: "blur" }],
  status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  sort: [
    { required: true, message: "排序值不能为空", trigger: "blur" },
    { validator: validNumber, message: "排序值只能是数字", trigger: "blur" }
  ]
});

// 打开弹窗
const show = (type, row) => {
  state.dialogVisible = true;
  state.operType = type;
  form.value.id = "";
  if (type === "add") {
    state.dialogTitle = "新增";
  } else if (type === "edit") {
    state.dialogTitle = "修改";
  } else if (type === "view") {
    state.dialogTitle = "查看";
  }
  // 获取DefFlow信息
  console.log("show", row);
  if (row) {
    Object.assign(form.value, row);
    if (form.value.orderIcon) {
      form.value.icon = JSON.parse(form.value.orderIcon);
    }
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;
  try {
    state.loading = true;
    form.value.orderIcon = JSON.stringify(form.value.icon);
    let res;
    if (form.value.id) {
      res = await updateObj(form.value);
    } else {
      res = await addObj(form.value);
    }
    if (res.code === 200) {
      useMessage().success("保存成功");
      close();
      emit("refresh");
    } else {
      useMessage().error(res.msg);
    }
  } catch (err) {
    useMessage().warning(err.msg);
  } finally {
    state.loading = false;
  }
};

const close = () => {
  state.dialogTitle = props.title;
  form.value = {
    id: "",
    orderName: "",
    flowKey: "",
    groupId: "",
    status: "-1",
    remark: "",
    sort: 1,
    orderIcon: "",
    flowWay: "0",
    version: null,
    defFlowId: "",
    formId: "",
    formName: "",
    icon: {
      name: "file-icons:omnigraffle",
      bgc: "#4C87F3",
      color: "#FFFFFF"
    }
  };
  state.dialogVisible = false;
};

const handleFlowChange = (key, item) => {
  form.value.flowKey = key;
  if (item) {
    form.value.version = item.version;
    form.value.defFlowId = item.id;
    form.value.formId = item.formId;
    form.value.formName = item.formName;
  }
};

// 暴露变量
defineExpose({
  show,
  close
});
</script>
